package com.orm_plus;

import com.orm.session.SqlSession;
import com.spring.aware.ApplicationContextAware;
import com.spring.context.impl.AbstractApplicationContext;
import com.spring.factory.FactoryBean;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class  MapperFactoryBean<T> implements FactoryBean<T>, ApplicationContextAware {
	private static AbstractApplicationContext ac;
	private static SqlSession sqlSession;
	

	private Class<T> mapperInterface;
	
	public MapperFactoryBean(Class<T> mapperInterface) {
		this.mapperInterface = mapperInterface;
	}
	
	@Override
	public T getObject() {
		if(sqlSession == null){
			SimpleSqlSessionFactory simpleSqlSessionFactory = (SimpleSqlSessionFactory)ac.getBean("sqlSessionFactory");
			sqlSession = simpleSqlSessionFactory.openSession();
		}
		
		// log.info("开始创建 {} 的代理mapper对象",mapperInterface.getName());
		T mapper = sqlSession.getMapper(this.mapperInterface);
		return mapper;
	}
	
	
	@Override
	public void setApplicationContext(AbstractApplicationContext applicationContext) {
		this.ac = applicationContext;
	}
}
